package org.eiahe.hr.salary.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.common.core.BaseController;
import org.ehe.common.core.domain.R;
import org.ehe.common.core.utils.StringUtils;
import org.ehe.common.core.validate.AddGroup;
import org.ehe.common.core.validate.EditGroup;
import org.ehe.common.core.validate.QueryGroup;
import org.ehe.common.log.annotation.Log;
import org.ehe.common.log.enums.BusinessType;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.eiahe.hr.salary.domain.bo.SalaryImportRecordBo;
import org.eiahe.hr.salary.domain.vo.SalaryImportRecordVo;
import org.eiahe.hr.salary.service.ISalaryImportRecordService;
import org.ehe.common.excel.utils.ExcelUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import cn.dev33.satoken.annotation.SaCheckPermission;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.List;

/**
 * 薪资导入记录Controller
 *
 * @author zhangnn
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/salary/importRecord")
public class SalaryImportRecordController extends BaseController {

    private final ISalaryImportRecordService iSalaryImportRecordService;

    /**
     * 查询薪资导入记录列表
     */
    @SaCheckPermission("salary:importRecord:list")
    @GetMapping("/list")
    public TableDataInfo<SalaryImportRecordVo> list(SalaryImportRecordBo bo, PageQuery pageQuery) {
        return iSalaryImportRecordService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出薪资导入记录列表
     */
    @SaCheckPermission("salary:importRecord:export")
    @Log(title = "薪资导入记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SalaryImportRecordBo bo, HttpServletResponse response) {
        List<SalaryImportRecordVo> list = iSalaryImportRecordService.queryList(bo);
        ExcelUtil.exportExcel(list, "薪资导入记录数据", SalaryImportRecordVo.class, response);
    }

    /**
     * 导出薪资模板
     */
    @SaCheckPermission("salary:importRecord:exportTemplate")
    @GetMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) {
        // 模板文件路径
        String templatePath = "/templates/salary_template.xlsx";

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=salary_template.xlsx");

        try {
            // 从classpath加载模板文件
            ClassPathResource resource = new ClassPathResource(templatePath);
            InputStream inputStream = resource.getInputStream();

            // 将文件写入响应
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();

            inputStream.close();
        } catch (IOException e) {
            log.error("导出薪资模板失败", e);
            throw new RuntimeException("导出薪资模板失败: " + e.getMessage());
        }
    }

    /**
     * 获取薪资导入记录详细信息
     *
     * @param recordId 主键
     */
    @SaCheckPermission("salary:importRecord:query")
    @GetMapping("/{recordId}")
    public R<SalaryImportRecordVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable("recordId") Long recordId) {
        return R.ok(iSalaryImportRecordService.queryById(recordId));
    }

    /**
     * 新增薪资导入记录
     */
    @SaCheckPermission("salary:importRecord:add")
    @Log(title = "薪资导入记录", businessType = BusinessType.INSERT)
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SalaryImportRecordBo bo) {
        return toAjax(iSalaryImportRecordService.insertByBo(bo));
    }

    /**
     * 修改薪资导入记录
     */
    @SaCheckPermission("salary:importRecord:edit")
    @Log(title = "薪资导入记录", businessType = BusinessType.UPDATE)
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SalaryImportRecordBo bo) {
        return toAjax(iSalaryImportRecordService.updateByBo(bo));
    }

    /**
     * 删除薪资导入记录
     *
     * @param recordIds 主键串
     */
    @SaCheckPermission("salary:importRecord:remove")
    @Log(title = "薪资导入记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{recordIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] recordIds) {
        return toAjax(iSalaryImportRecordService.deleteWithValidByIds(Arrays.asList(recordIds)));
    }

    /**
     * 导入薪资数据
     */
    @SaCheckPermission("salary:importRecord:import")
    @Log(title = "薪资导入", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public R<Long> importSalaryData(@RequestParam("file") MultipartFile file,
            @RequestParam("yearMonth") String yearMonth) {
        Long recordId = iSalaryImportRecordService.importSalaryData(file, yearMonth);
        return R.ok(recordId);
    }

    /**
     * 重试导入失败的记录
     *
     * @param recordId 导入记录ID
     */
    @SaCheckPermission("salary:importRecord:retry")
    @Log(title = "薪资导入", businessType = BusinessType.UPDATE)
    @PostMapping("/retry/{recordId}")
    public R<Void> retryImport(@PathVariable Long recordId) {
        return toAjax(iSalaryImportRecordService.retryImport(recordId));
    }

    /**
     * 回滚导入的数据
     *
     * @param recordId 导入记录ID
     */
    @SaCheckPermission("salary:importRecord:rollback")
    @Log(title = "薪资导入", businessType = BusinessType.DELETE)
    @DeleteMapping("/rollback/{recordId}")
    public R<Void> rollbackImport(@PathVariable Long recordId) {
        return toAjax(iSalaryImportRecordService.rollbackImport(recordId));
    }
}
